package com.project.util;

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Component
public class PowerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从header中获取到token
        String token= request.getHeader("token");
        //验证token
        String json=  SysToken.verifierJwt(token);
        if(!json.equals("error")){
            JSONObject jsonObject=    JSONObject.parseObject(json);
            Map mapUser= (Map) jsonObject.get("user");
            //获得用户拥有的权限
            List<JSONObject> powerList= (List) jsonObject.get("powerList");
            String userName= (String) mapUser.get("username");
            System.out.println(userName);

            for(JSONObject object:powerList){
                String power= (String) object.get("name");
                //该系统的权限是info3
                if(power.equals("info1")){
                    return  true;
                }
                if(power.equals("info2")){
                    return  true;
                }
                if(power.equals("info3")){
                    return  true;
                }
            }
        }

        //获取token权限，验证权限  info1

        return  false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
